// 认证中间件
const jwt = require('jsonwebtoken');
const { User } = require('../models');

// JWT密钥（实际应用中应该从环境变量读取）
const JWT_SECRET = 'your_jwt_secret_key';

// 验证JWT token的中间件
exports.verifyToken = (req, res, next) => {
  // 从cookie中获取token
  const token = req.cookies['auth_token'];
  
  if (!token) {
    return res.redirect('/admin/login');
  }

  try {
    // 验证token
    const decoded = jwt.verify(token, JWT_SECRET);
    req.userId = decoded.userId;
    next();
  } catch (err) {
    return res.redirect('/admin/login');
  }
};

// 检查用户是否是管理员的中间件
exports.isAdmin = async (req, res, next) => {
  try {
    const user = await User.findByPk(req.userId);
    if (!user || !user.isAdmin) {
      return res.status(403).json({ message: '需要管理员权限' });
    }
    next();
  } catch (err) {
    return res.status(500).json({ message: '服务器错误' });
  }
};

// 可选的验证，用于获取当前用户信息
exports.getUserFromToken = async (req, res, next) => {
  const token = req.cookies['auth_token'];
  
  if (token) {
    try {
      const decoded = jwt.verify(token, JWT_SECRET);
      const user = await User.findByPk(decoded.userId, {
        include: ['membershipLevel']
      });
      req.user = user;
    } catch (err) {
      // token无效时忽略
      req.user = null;
    }
  }
  
  next();
};

// 生成JWT token
exports.generateToken = (userId) => {
  return jwt.sign({ userId }, JWT_SECRET, { expiresIn: '24h' });
};